import os 
import numpy as np
import re
import shutil
from tqdm import tqdm


def process_label(alllabelfilepath, xx):
    sketch_label = os.path.join(alllabelfilepath, xx, 'labels.npy')
    labels = np.load(sketch_label, allow_pickle=True)
    labels = np.array(labels)

    # Extract detection labels for each frame from labels
    labellist = []
    for i in range(len(labels)):
        if labels[i].numel():
            _, indices = labels[i][0].topk(k=5)
            labellist.append(list(np.array(indices)))

    for i in range(len(labellist)):
        sit = 10
        stand = 11
        walk = 13
        if sit in labellist[i]:
            labellist[i] = 10
        elif stand in labellist[i]:
            labellist[i] = 11
        elif walk in labellist[i]:
            labellist[i] = 13
        else:
            labellist[i] = labellist[i][0]

    for i in range(1, len(labellist) - 1):
        if labellist[i] != labellist[i - 1] and labellist[i] != labellist[i + 1] and labellist[i - 1] == labellist[i + 1]:
            labellist[i] = labellist[i - 1]

    result_index = []
    start = 0
    for i in range(1, len(labellist)):
        if labellist[i] != labellist[i - 1]:
            if i - start > 1:
                result_index.append([start, i])
            else:
                result_index.append([start])
            start = i

    # Process the last continuous segment
    if len(labellist) - start > 1:
        result_index.append([start, len(labellist)])
    else:
        result_index.append([start])

    for i in range(len(result_index)):
        for j in range(len(result_index[i])):
            result_index[i][j] = result_index[i][j] * 64 + 31

    videoframe = os.path.join(alllabelfilepath, xx, 'frame.pkl')

    # Open the pickle file and read the object
    with open(videoframe, 'rb') as f:
        frame = pickle.load(f)

    startandendtimestamp = []
    startandendindex = []
    for i in result_index:
        if len(i) > 1:
            x = []
            xindex = []
            for j in i:
                if j > len(frame) - 1:
                    x.append(frame[len(frame) - 1].timestamp())
                    xindex.append(len(frame) - 1)
                else:
                    x.append(frame[j].timestamp())
                    xindex.append(j)
            startandendindex.append(xindex)
            startandendtimestamp.append(x)

    end2 = frame[-1].timestamp()
    print(end2 == startandendtimestamp[-1][-1])

    if end2 > startandendtimestamp[-1][-1]:
        startandendtimestamp.append([startandendtimestamp[-1][-1], end2])

    startandendtimestamp = np.array(startandendtimestamp)

    savetimestamp = os.path.join(alllabelfilepath, xx, 'timestamp.npy')
    np.save(savetimestamp, startandendtimestamp)